var express = require('express')
var router = express.Router()
var https = require('https')
var MongoClient = require('mongodb').MongoClient
var url = "mongodb://127.0.0.1:27017"
// 根据用户的 ip 地址进行定位
router.get('/ip', function(req,res,next){
    console.log('哈哈')
    https.get('https://apis.map.qq.com/ws/location/v1/ip?key=NOSBZ-23ZRI-TI7GQ-55SHN-PJMD3-2XFGT', function(response){
        var data = "";   
        response.on("data",function(chunk){
            data += chunk
        })
        response.on("end",function(){
            res.send(data);
        })
    })

})
// 获取城市信息
router.get('/city',function(req,res,next){
   var result = {}   // 返回给前端的信息 
  // 连接数据库进行查询
  MongoClient.connect(url, { useNewUrlParser: true }, function(error,client){
      if(error){
        result.status = 1;
        result.msg = '网络错误'
        res.json(result);
        return;
      }
      // 如果数据库连接成功
      var db = client.db('maizuo');
      db.collection('city').find().toArray(function(error,data){
          if(error){
              console.log('数据库查询失败');
              result.msg = '网络错误，请稍后重试';
              result.status = 1;
          } else {
              result.msg = 'ok';
              result.status = 0;
              result.data = data;
          }
          // 将数据返回前端
          res.json(result);
          client.close();
      });
  })  
})
module.exports = router